#include "../Include/GcpConnector.h"
#include "../Include/GcpClientEvent.h"

CGcpConnector::CGcpConnector(CEventEngine *pEngine)
    : m_connector(pEngine)
{
    m_pCallback = NULL;
    m_pEngine = pEngine;
}

CGcpConnector::~CGcpConnector()
{
}

Bool CGcpConnector::Connect(const CSocketAddr &server, Int32 nTimeout, IGcpConnectorCallback *pCallback)
{
    m_pCallback = pCallback;
    return m_connector.Connect(server, this, nTimeout);
}

void CGcpConnector::OnConnected()
{
    CSocketAddr addr = SocketUtil::GetRemoteAddress(m_connector.GetFD());
    CGcpClientEvent *pClientEvent = new CGcpClientEvent(m_connector.GetFD(), addr, m_pEngine, this);
    CGcpProxyPtr spProxy(new CGcpProxy(pClientEvent));

    IGcpHandler *pHandler = m_pCallback->OnGcpConnected(spProxy);
    pClientEvent->SetHandler(pHandler);
    pClientEvent->SetProxy(spProxy);

    m_connector.Detach();
}

void CGcpConnector::OnConnectFailed(Int32 nError)
{
    m_pCallback->OnGcpConnectError(nError);
}

void CGcpConnector::OnConnectTimeout()
{
    m_pCallback->OnGcpConnectError(0);
}

void CGcpConnector::DispatchMessage(CClientEvent *pClientEvent, void *pMsg)
{
    pClientEvent->HandleMessage(pMsg, False);
}
